let app = getApp();
function requestUrl(data, uri) {
  let that = this
  return new Promise(function(resolve, reject) {
    wx.request({
      url: uri,
      method: 'GET',
      data: data,
      success: function(res) {
        resolve(res.data)
      },
      fail: function() {
        wx.showToast({
          title: '网络错误',
          duration: 1000
        })
      },
      header: {
        'X-TOKEN': wx.getStorageSync('openId') || '',
		'X-ACCOUNTID': wx.getStorageSync('userinfo').id || ''
      }
    })
  })
}

function requestPostUrl(data, uri) {
  let that = this
  data['action_id'] = wx.getStorageSync('openId') || ''
  return new Promise(function(resolve, reject) {
    wx.request({
      url: uri,
      method: 'POST',
      data: data,
      complete: function(res) {
        resolve(res.data)
      },
      header: {
        Cookie: `JSESSIONID=${wx.getStorageSync('openId') || ''}`,
        'X-TOKEN': wx.getStorageSync('openId') || ''
      }
    })
  })
}

function requestUrlSession(data, uri) {
  let that = this
  return new Promise(function(resolve, reject) {
    wx.request({
      url: uri,
      method: 'GET',
      data: data,
      complete: function(res) {
        resolve(res)
      }
    })
  })
}

function showSuccess(msg) {
  wx.showToast({
    title: msg,
    duration: 1000
  })
}

function showError(msg,time=1000) {
  wx.showToast({
    title: msg,
    duration: time,
    icon: 'none'
  })
}

function chooseimage(count, files, name, url) {
  let that = this
  return new Promise(function(resolve, reject) {
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      count: count,
      success: function(res) {
        if (res.tempFilePaths.length + files.length > count) {
          that.showError('请上传少于' + count + '张图片')
        } else {
          Promise.all(res.tempFilePaths.map((fileurl) => {
            return new Promise(function(resolve, reject) {
              wx.uploadFile({
                url: url,
                filePath: fileurl,
                name: name,
                formData: {
                  'type': name
                },
                success: function(res) {
                  if (res.statusCode === 200) {
                    resolve(res.data)
                  }
                }

              })
            })
          })).then(res => {
            resolve(res)
          })
        }
      }
    })


  })
}

function ageshare() {
  var data = { account_id: wx.getStorageSync('userinfo').id }
  var url = app.u.H + app.u.river.SHAREINDEX
  this.requestUrl(data, url)
}


module.exports = {
  showSuccess: showSuccess,
  showError: showError,
  requestUrl: requestUrl,
  requestUrlSession: requestUrlSession,
  chooseimage: chooseimage,
  requestPostUrl: requestPostUrl,
  ageshare: ageshare
}